<template>
  <div class="app-container">
    <el-form
      ref="form"
      :model="form"
      label-width="80px"
      :inline="true"
      size="small"
    >
      <el-form-item label="操作时间">
        <el-date-picker
          type="date"
          placeholder="选择时间"
          v-model="form.beginTime"
          style="width: 260px"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          type="date"
          placeholder="选择时间"
          v-model="form.endTime"
          style="width: 260px"
          value-format="yyyy-MM-dd HH:mm:ss"
        ></el-date-picker>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="inquire" size="mini">查询</el-button>
        <el-button type="primary" size="mini" @click="newCard"
          >新增批次</el-button
        >
      </el-form-item>
    </el-form>

    <el-table :data="cardList" border style="width: 100%" v-loading="loading">
      <el-table-column label="序号" type="index" width="65" align="left" />
      <el-table-column prop="batchNo" label="批次" align="left" />
      <el-table-column
        prop="batchType"
        label="卡类型"
        align="left"
        :formatter="formatterPayType"
      />
      <el-table-column prop="cardNum" label="卡片数量" align="left" />
      <el-table-column prop="totalNum" label="已写数量" align="left" />
      <el-table-column prop="createTime" label="操作时间" align="left" />
      <el-table-column fixed="right" label="操作" width="170" align="left">
        <template slot-scope="scope">
          <el-popconfirm
            title="是否确定导出卡号？"
            @onConfirm="exporCard(scope.row)"
          >
            <el-button type="text" size="small" slot="reference">
              导出卡号
            </el-button>
          </el-popconfirm>
          <el-button
            type="text"
            size="small"
            @click="editing(scope.row)"
            style="margin: 0px 10px"
          >
            写卡
          </el-button>
          <el-popconfirm
            title="是否确定删除？"
            @onConfirm="buttonDelete(scope.row)"
          >
            <el-button type="text" size="small" slot="reference"
              >删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 20px"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="this.pageNum"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="this.pageSize"
      layout="->,total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <el-drawer
      size="50%"
      title="新增批次"
      :visible.sync="newDrawer"
      :before-close="newCloseDrawer"
    >
      <div style="margin-left: 8%">
        <el-form
          :model="formNewCard"
          ref="formNewCardRef"
          :rules="formNewCardRules"
          :label-position="labelPosition"
        >
          <el-form-item label="发卡数量：" prop="cardNum">
            <el-input
              maxlength="6"
              size="medium"
              style="width: 500px"
              v-model.number="formNewCard.cardNum"
            ></el-input>
          </el-form-item>
          <el-form-item label="起始序号：" prop="writeNum">
            <el-input
              maxlength="6"
              size="medium"
              style="width: 500px"
              v-model.number="formNewCard.writeNum"
            ></el-input>
          </el-form-item>
          <el-form-item label="卡类型：" prop="batchType">
            <el-select
              size="medium"
              style="width: 500px"
              v-model="formNewCard.batchType"
              placeholder="请选择卡类型"
              multiple
            >
              <el-option label="通用卡" value="0"></el-option>
              <el-option label="汽油卡" value="1"></el-option>
              <el-option label="柴油卡" value="2"></el-option>
              <el-option label="LNG" value="3"></el-option>
              <el-option label="CNG" value="4"></el-option>
            </el-select>
          </el-form-item>
          <el-button
            size="small"
            type="primary"
            style="position: relative; left: 450px; bottom: -10px"
            @click="saveNew('formNewCardRef')"
          >
            保存
          </el-button>
        </el-form>
      </div>
    </el-drawer>
    <el-drawer
      size="50%"
      title="写卡"
      :visible.sync="drawer"
      :before-close="writeCloseDrawer"
    >
      <div style="margin-left: 8%">
        <el-form :model="formWrite" ref="formWriteRef" :rules="formWriteRules">
          <el-form-item label="卡号：" prop="physicalCardNo">
            <el-input
              maxlength="24"
              size="medium"
              style="width: 380px"
              v-model="formWrite.physicalCardNo"
            ></el-input>
          </el-form-item>
          <el-button
            :disabled="isCard || isdisabled === this.formWrite.physicalCardNo"
            size="small"
            type="primary"
            class="card-button"
            @click="writePrevious('formWriteRef')"
          >
            上一张
          </el-button>
          <el-button
            :disabled="isCard"
            size="small"
            type="primary"
            class="card-button"
            @click="writeNext('formWriteRef')"
          >
            下一张
          </el-button>
        </el-form>
        <div style="margin-left: 8%; margin-top: 20px">
          成功 <span class="card-span">{{ physicalCardNoList.length }}</span> 条
        </div>
        <div class="write-cards">
          <ul class="card-ul">
            <li v-for="item in physicalCardNoList" style="margin-bottom: 8px">
              {{ item }}
            </li>
          </ul>
        </div>
        <el-button
          size="small"
          type="primary"
          style="margin-left: 480px"
          @click="saveWrite('formWriteRef')"
        >
          保存
        </el-button>
        <el-button size="small" type="primary" @click="cancelWrite">
          取消
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  list,
  cardDelete,
  saveNewCard,
  physicalCardNo,
  getCardNo,
  firstNum,
  statusCard,
  getSecretKey,
  judgeCard,
} from "@/api/ic/card";
import RFIDReader from "./util/RFIDReader";
import ReaderFunction from "./util/ReaderFunction";
export default {
  name: "Card_StoredValue",
  data() {
    var validatePass1 = (rule, value, callback) => {
      if (value < 0) return callback(new Error("发卡数量不能小于0"));
      if (value == 0) return callback(new Error("发卡数量不能为0"));
      if (value > 100000) return callback(new Error("发卡数量最大为100000"));
      let amount = Number(String(value).trim());
      if (!value && value !== 0) return callback(new Error("请输入发卡数量"));
      if (String(value).startsWith("."))
        return callback(new Error("请输入有效数值"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      callback();
    };
    var validatePass2 = (rule, value, callback) => {
      if (value < 0) return callback(new Error("起始卡号不能小于0"));
      if (value > 100000) return callback(new Error("起始卡号最大为100000"));
      let amount = Number(String(value).trim());
      if (!value && value !== 0) return callback(new Error("请输入起始卡号"));
      if (String(value).startsWith("."))
        return callback(new Error("请输入有效数值"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      callback();
    };
    var validatePass3 = (rule, value, callback) => {
      let amount = Number(String(value).trim());
      if (!value && value !== 0) return callback(new Error("请输入"));
      if (String(value).startsWith("."))
        return callback(new Error("请输入有效数值"));
      if (Number.isNaN(amount)) return callback(new Error("请输入合法数字"));
      callback();
    };
    var validatePass4 = (rule, value, callback) => {
      if (value.length === 0) {
        callback(new Error("请选择卡类型"));
      } else {
        callback();
      }
    };
    return {
      secretData: null,
      isdisabled: null,
      isCard: false,
      physicalCardNoList: [],
      cardInfo: null,
      cardList: [],
      loading: false,
      total: null,
      pageNum: 1,
      pageSize: 10,
      labelPosition: "top",

      newDrawer: false,
      drawer: false,
      formNewCard: {
        cardNum: null,
        writeNum: null,
        batchType: [],
      },
      formWrite: {
        physicalCardNo: null,
        numberString: null,
      },
      form: {
        physicalCardType: "czk",
        beginTime: null,
        endTime: null,
      },
      formNewCardRules: {
        cardNum: [{ validator: validatePass1, trigger: "change" }],
        writeNum: [{ validator: validatePass2, trigger: "change" }],
        batchType: [{ validator: validatePass4, trigger: "change" }],
      },
      formWriteRules: {
        physicalCardNo: [{ validator: validatePass3, trigger: "change" }],
      },
      ruleForm: {
        device: "0",
        blockNumber: 1,
        scretKey: "FFFFFFFFFFFF",
        scretVal: "000000000000ff078069ffffffffffff",
      },
    };
  },
  created() {
    this.inquire();
    this.secretKey();
  },
  methods: {
    // 获取密钥
    secretKey() {
      // 333762303466ff078069613165626430
      // FFFFFFFFFFFFff078069ffffffffffff
      // 00000000000000000000000000000000
      getSecretKey().then((res) => {
        let secretKeyA = ReaderFunction.stringToHex(res.data.secretKeyA);
        let secretKeyB = ReaderFunction.stringToHex(res.data.secretKeyB);
        let scretVal = this.ruleForm.scretVal;
        scretVal = scretVal.substring(12, 20);
        this.secretData = secretKeyA + scretVal + secretKeyB;
      });
    },
    // 管理卡列表
    gitList() {
      this.loading = true;
      let endTime = null;
      if (this.form.endTime) {
        endTime = this.form.endTime + "";
        endTime = endTime.replace("00:00:00", "23:59:59");
      }
      list({
        ...this.form,
        endTime,
        pageNum: this.pageNum,
        pageSize: this.pageSize,
      }).then((res) => {
        this.cardList = res.rows;
        this.total = res.total;
        this.loading = false;
      });
    },

    // 点击新增批次
    newCard() {
      this.newDrawer = true;
    },

    // 新增抽屉关闭
    newCloseDrawer() {
      this.newDrawer = false;
      this.$refs["formNewCardRef"].resetFields();
    },

    // 点击写卡
    editing(row) {
      firstNum({ id: row.id }).then((res) => {
        if (res.code === 200) {
          this.drawer = true;
          this.cardInfo = res;
          this.formWrite.physicalCardNo = res.data.physicalCardNo;
          this.formWrite.numberString = this.formWrite.physicalCardNo.length;
          this.isdisabled = res.data.physicalCardNo;
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    //写卡
    cardReading(num) {
      let _this = this;
      if (_this.physicalCardNoList.includes(_this.formWrite.physicalCardNo)) {
        _this.$message.error("重复卡号");
        _this.formWrite.physicalCardNo =
          parseInt(_this.formWrite.physicalCardNo) + num + "";
        _this.isCard = false;
      } else {
        ReaderFunction.OpenDevice(0, function (res) {
          if (res.data.device_id == -1) {
            _this.$message.error("未连接设备");
            _this.isCard = false;
          } else {
            ReaderFunction.TyA_GetUID(0, function (result) {
              console.log("查看是否链接", result);
              if (result.data.snr) {
                ReaderFunction.TyA_CS_Read2(
                  parseInt(_this.ruleForm.device),
                  3,
                  _this.ruleForm.scretKey,
                  function (result) {
                    console.log("原始密钥，3块号区读卡", result);
                    if (result.data) {
                      console.log("使用原始密钥可以读取成功");
                      ReaderFunction.TyA_CS_Write2(
                        parseInt(_this.ruleForm.device),
                        3,
                        _this.ruleForm.scretKey,
                        _this.secretData,
                        function (result) {
                          console.log("重置密钥成功", result);
                          if (result.retval == 0) {
                            console.log("重置密钥成功");
                            ReaderFunction.TyA_CS_Read2(
                              parseInt(_this.ruleForm.device),
                              _this.ruleForm.blockNumber,
                              _this.secretData,
                              function (result) {
                                console.log(
                                  "重置密钥成功,使用新密钥读取卡",
                                  result
                                );

                                let physicalCardNo2 =
                                  ReaderFunction.hexToString(result.data.value);
                                if (
                                  _this.physicalCardNoList.includes(
                                    physicalCardNo2.replaceAll("\x00", "")
                                  )
                                ) {
                                  _this.$message.error("重复写卡");
                                  _this.isCard = false;
                                } else {
                                  if (result !== null) {
                                    let physicalCardNo;
                                    let physical = ReaderFunction.stringToHex(
                                      _this.formWrite.physicalCardNo + ""
                                    );
                                    if (physical.length !== 32) {
                                      if (physical.length > 32) return;
                                      const cardNo = 32 - physical.length;
                                      let no = "";
                                      for (let i = 0; i < cardNo; i++) {
                                        no = no + "0";
                                      }
                                      physicalCardNo = no + physical;
                                    }
                                    ReaderFunction.TyA_CS_Write2(
                                      parseInt(_this.ruleForm.device),
                                      _this.ruleForm.blockNumber,
                                      _this.secretData,
                                      physicalCardNo,
                                      function (result) {
                                        if (result !== null) {
                                          if (result.retval === 0) {
                                            // 蜂鸣
                                            RFIDReader.Sys_SetBuzzer(
                                              RFIDReader.device_id,
                                              20,
                                              null
                                            );
                                            let physicalCardNo1 =
                                              ReaderFunction.hexToString(
                                                physicalCardNo
                                              );

                                            console.log(
                                              "physicalCardNo1",
                                              physicalCardNo1
                                            );

                                            let physicalCardNo2 =
                                              physicalCardNo1.replaceAll(
                                                "\x00",
                                                ""
                                              );

                                            console.log(
                                              "physicalCardNo2",
                                              physicalCardNo2
                                            );

                                            _this.physicalCardNoList.unshift(
                                              physicalCardNo2
                                            );
                                            statusCard([
                                              {
                                                physicalCardNo:
                                                  _this.formWrite
                                                    .physicalCardNo,
                                                isSuccess: "1",
                                              },
                                            ]).then((res) => {
                                              if (res && res.code === 200) {
                                                _this.$message.success(res.msg);
                                              } else {
                                                _this.$message.error(res.msg);
                                              }
                                            });

                                            let physicalCardNo4 =
                                              parseInt(
                                                _this.formWrite.physicalCardNo
                                              ) + num;

                                            console.log(
                                              "physicalCardNo4",
                                              physicalCardNo4
                                            );

                                            let physicalCardNo5 =
                                              physicalCardNo4 + "";

                                            let physicalCardNo6;

                                            if (
                                              _this.formWrite.physicalCardNo
                                                .length > physicalCardNo5.length
                                            ) {
                                              const cardNo =
                                                _this.formWrite.physicalCardNo
                                                  .length -
                                                physicalCardNo5.length;
                                              let no = "";
                                              for (let i = 0; i < cardNo; i++) {
                                                no = no + "0";
                                              }
                                              physicalCardNo6 =
                                                no + physicalCardNo5;
                                              console.log("补几个零", cardNo);
                                            } else {
                                              physicalCardNo6 = physicalCardNo5;
                                            }

                                            console.log(
                                              "physicalCardNo5",
                                              physicalCardNo5
                                            );

                                            console.log(
                                              "physicalCardNo6",
                                              physicalCardNo6
                                            );

                                            _this.formWrite.physicalCardNo =
                                              physicalCardNo6;

                                            _this.isCard = false;
                                          } else {
                                            _this.$message.error("写卡失败");
                                            _this.isCard = false;
                                          }
                                        } else {
                                          _this.$message.error("写卡失败");
                                          _this.isCard = false;
                                        }
                                      }
                                    );
                                  } else {
                                    _this.$message.error("读卡失败");
                                    _this.isCard = false;
                                  }
                                }
                              }
                            );
                          } else {
                            _this.$message.error("重置密钥失败");
                            _this.isCard = false;
                          }
                        }
                      );
                    } else {
                      ReaderFunction.TyA_CS_Read2(
                        parseInt(_this.ruleForm.device),
                        _this.ruleForm.blockNumber,
                        _this.secretData,
                        function (result) {
                          if (result.data) {
                            console.log("使用新密钥读取卡，1块区号", result);
                            let physicalCardNo2 = ReaderFunction.hexToString(
                              result.data.value
                            );
                            judgeCard({
                              physicalCardNo: physicalCardNo2,
                            }).then((res) => {
                              if (res && res.code === 200) {
                                if (res.data) {
                                  if (
                                    _this.physicalCardNoList.includes(
                                      physicalCardNo2.replaceAll("\x00", "")
                                    )
                                  ) {
                                    _this.$message.error("重复写卡");
                                    _this.isCard = false;
                                  } else {
                                    let physicalCardNo;
                                    let physical = ReaderFunction.stringToHex(
                                      _this.formWrite.physicalCardNo + ""
                                    );
                                    if (physical.length !== 32) {
                                      if (physical.length > 32) return;
                                      const cardNo = 32 - physical.length;
                                      let no = "";
                                      for (let i = 0; i < cardNo; i++) {
                                        no = no + "0";
                                      }
                                      physicalCardNo = no + physical;
                                    }
                                    ReaderFunction.TyA_CS_Write2(
                                      parseInt(_this.ruleForm.device),
                                      _this.ruleForm.blockNumber,
                                      _this.secretData,
                                      physicalCardNo,
                                      function (result) {
                                        if (result !== null) {
                                          if (result.retval === 0) {
                                            // 蜂鸣
                                            RFIDReader.Sys_SetBuzzer(
                                              RFIDReader.device_id,
                                              20,
                                              null
                                            );
                                            let physicalCardNo1 =
                                              ReaderFunction.hexToString(
                                                physicalCardNo
                                              );

                                            console.log(
                                              "physicalCardNo1",
                                              physicalCardNo1
                                            );

                                            let physicalCardNo2 =
                                              physicalCardNo1.replaceAll(
                                                "\x00",
                                                ""
                                              );

                                            console.log(
                                              "physicalCardNo2",
                                              physicalCardNo2
                                            );

                                            _this.physicalCardNoList.unshift(
                                              physicalCardNo2
                                            );
                                            statusCard([
                                              {
                                                physicalCardNo:
                                                  _this.formWrite
                                                    .physicalCardNo,
                                                isSuccess: "1",
                                              },
                                            ]).then((res) => {
                                              if (res && res.code === 200) {
                                                _this.$message.success(res.msg);
                                              } else {
                                                _this.$message.error(res.msg);
                                              }
                                            });

                                            let physicalCardNo4 =
                                              parseInt(
                                                _this.formWrite.physicalCardNo
                                              ) + num;

                                            console.log(
                                              "physicalCardNo4",
                                              physicalCardNo4
                                            );

                                            let physicalCardNo5 =
                                              physicalCardNo4 + "";

                                            let physicalCardNo6;

                                            if (
                                              _this.formWrite.physicalCardNo
                                                .length > physicalCardNo5.length
                                            ) {
                                              const cardNo =
                                                _this.formWrite.physicalCardNo
                                                  .length -
                                                physicalCardNo5.length;
                                              let no = "";
                                              for (let i = 0; i < cardNo; i++) {
                                                no = no + "0";
                                              }
                                              physicalCardNo6 =
                                                no + physicalCardNo5;
                                              console.log("补几个零", cardNo);
                                            } else {
                                              physicalCardNo6 = physicalCardNo5;
                                            }

                                            console.log(
                                              "physicalCardNo5",
                                              physicalCardNo5
                                            );

                                            console.log(
                                              "physicalCardNo6",
                                              physicalCardNo6
                                            );

                                            _this.formWrite.physicalCardNo =
                                              physicalCardNo6;

                                            _this.isCard = false;
                                          } else {
                                            _this.$message.error("写卡失败");
                                            _this.isCard = false;
                                          }
                                        } else {
                                          _this.$message.error("写卡失败");
                                          _this.isCard = false;
                                        }
                                      }
                                    );
                                  }
                                } else {
                                  _this.$message.error(res.msg);
                                  _this.isCard = false;
                                }
                              } else {
                                _this.$message.error(res.msg);
                                _this.isCard = false;
                              }
                            });
                          } else {
                            _this.$message.error("读卡失败");
                            _this.isCard = false;
                          }
                        }
                      );
                    }
                  }
                );
              } else {
                _this.$message.error("读卡失败，检查是否放置卡");
                _this.isCard = false;
              }
            });
          }
        });
      }
    },

    // 点击查询
    inquire() {
      this.gitList();
    },

    // 点击导出卡号
    exporCard(row) {
      physicalCardNo({ id: row.id }).then((res) => {
        if (res && res.code === 200) {
          this.$message.success("导出成功");
          this.download(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 点击删除
    buttonDelete(row) {
      cardDelete({ id: row.id }).then((res) => {
        if (res && res.code === 200) {
          this.inquire();
          this.$message.success(res.msg);
        } else {
          this.$message.error(res.msg);
        }
      });
    },

    // 新增保存
    saveNew(formNewCardRef) {
      this.$refs[formNewCardRef].validate((valid) => {
        if (valid) {
          const batchType = this.formNewCard.batchType.join();
          saveNewCard({
            ...this.formNewCard,
            batchType,
            physicalCardType: this.form.physicalCardType,
          }).then((res) => {
            if (res && res.code === 200) {
              this.inquire();
              this.newDrawer = false;
              this.$message.success(res.msg);
              this.$refs["formNewCardRef"].resetFields();
            } else {
              this.$message.error(res.msg);
            }
          });
        } else {
          return false;
        }
      });
    },

    // 写卡上一张
    writePrevious(formWriteRef) {
      this.$refs[formWriteRef].validate((valid) => {
        if (valid) {
          this.getCardNo(-1);
        } else {
          return false;
        }
      });
    },

    // 写卡下一张
    writeNext(formWriteRef) {
      this.$refs[formWriteRef].validate((valid) => {
        if (valid) {
          this.getCardNo(1);
        } else {
          return false;
        }
      });
    },

    // 查询数据库有没有这个卡
    getCardNo(num) {
      this.isCard = true;
      judgeCard({ physicalCardNo: this.formWrite.physicalCardNo })
        .then((res) => {
          this.isCard = false;
          if (res && res.code === 200) {
            if (res.data) {
              this.cardReading(num);
            } else {
              this.$message.error(res.msg);
            }
          } else {
            this.$message.error(res.msg);
          }
        })
        .catch(() => {
          this.isCard = false;
        });
    },

    // 写卡保存
    saveWrite() {
      this.isCard = false;
      this.physicalCardNoList = [];
      this.formWrite.physicalCardNo = null;
      this.drawer = false;
      this.inquire();
      this.$message.success("已保存！");
    },

    // 写卡取消
    cancelWrite() {
      this.isCard = false;
      this.physicalCardNoList = [];
      this.formWrite.physicalCardNo = null;
      this.drawer = false;
      this.inquire();
      this.$refs["formWriteRef"].resetFields();
    },

    // 写卡抽屉关闭
    writeCloseDrawer() {
      this.isCard = false;
      this.physicalCardNoList = [];
      this.formWrite.physicalCardNo = null;
      this.drawer = false;
      this.inquire();
      this.$refs["formWriteRef"].resetFields();
    },

    // 分页
    handleSizeChange(val) {
      this.pageSize = val;
      this.inquire();
    },
    handleCurrentChange(val) {
      this.pageNum = val;
      this.inquire();
    },

    // 格式化支付类型
    formatterPayType(row, column) {
      let type = "";
      let batchType = row.batchType.split(",");
      if (batchType.length == 0) {
        return "";
      } else {
        batchType.forEach((item) => {
          if (item == 0) {
            type = type + "通用卡" + `${batchType.length == 1 ? "" : " , "}`;
          } else if (item == 1) {
            type = type + "汽油卡" + `${batchType.length == 1 ? "" : " , "}`;
          } else if (item == 2) {
            type = type + "柴油卡" + `${batchType.length == 1 ? "" : " , "}`;
          } else if (item == 3) {
            type = type + "LNG" + `${batchType.length == 1 ? "" : " , "}`;
          } else if (item == 4) {
            type = type + "CNG" + `${batchType.length == 1 ? "" : " , "}`;
          }
        });
      }
      return type;
    },
  },
};
</script>
<style style scoped lang="scss">
.card-ul {
  list-style: none;
  margin: 0px 10px;
  padding: 0px;
}

.write-cards {
  padding: 10px 5px;
  width: 545px;
  height: 350px;
  border: 1px solid #a3a3a37b;
  margin: 30px 0px 40px 55px;
  overflow-y: scroll;
}

.card-span {
  font-size: 17px;
  font-weight: bold;
}

.card-button {
  position: relative;
  top: -66px;
  right: -450px;
}

::v-deep .el-form--label-top .el-form-item__label {
  padding: 0px;
}

::v-deep .el-form {
  height: 55px;
}
</style>
